package com.java2104.service;

import com.java2104.entity.User;
import com.java2104.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public Map modifyPassword(User user,String oldPass,String newPass){
        //判断旧密码是否正确
        Map map = new HashMap();
        if(oldPass!=null && oldPass.equals(user.getPassword())){
            //旧密码正确
            user.setPassword(newPass);//设置新密码
            userMapper.updatePassword(user);
            map.put("status","success");
            map.put("msg","密码修改成功");
        }else {
            //旧密码错误
            map.put("status","fail");
            map.put("msg","旧密码输入不正确");
        }
        return map;
    }

    public User login(String loginname,String password){
        User user = userMapper.findByLoginname(loginname);
        if(user!=null){
            if(password!=null && password.equals(user.getPassword())) {//密码正确
                return user;//返回查到的用户
            }
        }
        return null;
    }

    public Map update(User user){
        Map map = new HashMap();
        if(userMapper.updateByPrimaryKey(user)>0){
            map.put("status","success");
            map.put("msg","用户信息修改成功");
        }else {
            map.put("status","fail");
            map.put("msg","用户信息修改失败");
        }
        return map;
    }
    public User get(Integer id){
        return userMapper.findByPrimaryKey(id);
    }
    public Map save(User user){
        Map ret = new HashMap();
        if(userMapper.exist(user.getLoginname())==0){
            userMapper.insert(user);//保存用户信息
            ret.put("status","success");
            ret.put("msg","添加成功");
        }else {
            ret.put("status","fail");
            ret.put("msg","该登录名重复，请更换其他登录名！");
        }
        return ret;
    }
    public List<User> getList(String loginname,Integer role){
        return userMapper.findList(loginname,role);
    }
    public void delete(List<Integer> ids){
        if(ids!=null && ids.size()>0){//非空判断，排除空集合
            userMapper.updateDeleteStatus(ids);
        }
    }
}
